define(function(require) {

    //include
    require('./list-tpl');
    require('./tab-tpl');
    require('../../../c/pagination/index');
    var orderDetail = require('../../../c/order-detail/index');


    var listTpl = juicer.templates['list.juicer.html'];
    var tabTpl = juicer.templates['tab.juicer.html'];


    var List = {

        //店铺id
        shopId: null,
        //城市代码
        cities: '',
        //订单时间
        gmt: '',
        //当前tab订单状态
        status: 1,
        //当前tab订单物流状态
        logisticStatus: '',
        //查询结果缓存
        cacheEntries: {},
        //当前tab页总数
        total: 0,
        //当前页号
        pageNum: 1,
        //每页大小
        pageSize: 10,
        //配送时间
        sendTimeRange: '',
        //是否禁用tab点击
        disabledTab: false,

        init: function() {
            //初始化菜单选中效果
            $(".fa-circle-o").each(function() {
                if ($(this).parents("a").text() == "订单监控") {
                    $(this).parents("a").parents("li").addClass("active");
                }
            });
            var self = this;
            self.queryOpenCity();
            self.initDatetimePicker();
            self.bindEvent();

            //默认时间
            var time = CRM.getUrlParam("time") || CRM.format(new Date(), 'yyyy-MM-dd');
            $('#gmtCreate').val(time);
            $('#gmtCreateStart').val(time);

            //urlParam shopId传入时
            var shopId = this.shopId = CRM.getUrlParam("id");
            if (shopId) {
                $('#search-input').val(shopId);
                this.searchVal = $('#search-input').val();
                this.queryShopId(function() {
                    self.renderTab();
                    self.queryOrderList();
                });
            }


            $('#tab').html(tabTpl({
                data: {
                    '1': '0',
                    '2': '0',
                    '3': '0',
                    '6': '0',
                    '7': '0'
                }
            }));

        },
        /**
         * 查询店铺开放城市
         */
        queryOpenCity: function() {
            var self = this;
            CRM.request({
                "type": 'POST',
                "url": CRM.API.queryOpenCity,
                "dataType": "json",
                "data": JSON.stringify({
                    "operator": $.cookie('_uk')
                }),
                "success": function(req) {
                    var entry = req.entry;
                    if (req.status) {
                        var allCities = "";
                        var snippets = [];
                        $.each(entry, function(index, item) {
                            allCities += item.cityCode + ",";
                            snippets.push("<option value='" + item.cityCode + "'>" + item.city + "</option>");
                        });
                        snippets.unshift("<option value='" + allCities + "'>全国</option>");
                        $("#search-city").html(snippets.join());
                    }
                }
            });
        },
        queryShopId: function(cb) {
            var self = this,
                type = $('#search-type').val();

            if (type == 'shopId') {
                this.shopId = this.searchVal;
                cb && cb();
            } else if (type == 'xiaoer' || type == 'xiaoerM') {
                this.queryShopByXiaoerId(cb);
            } else if (type == 'shopName') {
                this.queryShopByName(cb);
            }
        },

        /**
         * 根据店铺名查询shopId
         * @param cb
         */
        queryShopByName: function(cb) {
            var self = this;
            CRM.request({
                "type": 'POST',
                "url": CRM.API.queryShopByName,
                "dataType": "json",
                "data": JSON.stringify({
                    "shopName": self.searchVal,
                    "operator": $.cookie('_uk'),
                    "pageBegin": 1,
                    "pageSize": 100
                }),
                "success": function(req) {
                    var entry = req.entry;
                    if (req.status) {
                        self.shopId = [];
                        $.each(entry, function(index, item) {
                            self.shopId.push(item.id);
                        });
                        cb && cb();
                    }
                }
            });
        },

        /**
         * 根据小二Id 和 小二主管Id 查询 shopId
         * @param cb
         */
        queryShopByXiaoerId: function(cb) {
            var self = this;
            CRM.request({
                "type": 'POST',
                "url": CRM.API.queryShopByXiaoerId,
                "dataType": "json",
                "data": JSON.stringify({
                    "xiaoerId": self.searchVal,
                    "operator": $.cookie('_uk'),
                    "pageBegin": 1,
                    "pageSize": 100
                }),
                "success": function(req) {
                    var entry = req.entry;
                    if (req.status && entry.length > 0) {
                        self.shopId = [];
                        $.each(entry, function(index, item) {
                            self.shopId.push(item.id);
                        });
                        cb && cb();
                    }
                }
            });
        },


        /**
         * 订单状态筛选区域tab  1.待接单，2待发货 3.已发货待确认，4已完成，5.已送达 ,6:待支付 ,7:配送中
         */
        renderTab: function() {
            var self = this,
                gmt = self.gmt = $('#gmtCreateStart').val();

            if (!$.isArray(this.shopId)) {
                if (this.shopId) {
                    this.shopId = [this.shopId];
                } else {
                    this.shopId = [];
                }
            }
            var cities = self.cities = $("#search-city").val();
            if (cities.indexOf(",") != -1) {
                cities = cities.split(",");
            } else {
                cities = [cities];
            }

            var _orderType;
            if (!self.searchVal) {
                _orderType = 1;
            }
            CRM.request({
                "type": 'POST',
                "url": CRM.API.queryOrderCount,
                "dataType": "json",
                "data": JSON.stringify({
                    "gmtCreateStart": gmt,
                    "gmtCreateEnd": gmt,
                    "operator": $.cookie('_uk'),
                    "orderType": _orderType,
                    "shopIdList": this.shopId,
                    "cityCodeList": cities
                }),
                "success": function(req) {
                    var entry = req.entry;
                    if (req.status) {
                        $('#tab').html(tabTpl({
                            data: entry
                        }));
                        //ajax加载数据过程中，禁用tab标签
                        $('a[data-toggle]').on('click', function(e) {
                            if(self.disabledTab){
                                return false;
                            }
                        });
                        $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
                            self.disabledTabFn();
                            self.status = $(e.target).attr('data-status');
                            self.logisticStatus = $(e.target).attr('data-logistic-status');
                            if (self.status == '3' || self.status == '7')
                                $('#dist_time_group').show();
                            else
                                $('#dist_time_group').hide();
                            self.total = $(e.target).attr('data-total');
                            self.initPagination();
                        });
                        //查询缓存清空
                        self.initCacheEntries();
                        //默认加载status==1
                        self.total = entry[1];
                        self.initPagination();
                    } else {
                        CRM.showDialog(req.message)
                    }
                }
            });
        },

        /**
         * 订单列表
         */
        queryOrderList: function() {
            var self = this,
                gmt = self.gmt;

            if (!$.isArray(this.shopId)) {
                if (this.shopId) {
                    this.shopId = [this.shopId];
                } else {
                    this.shopId = [];
                }
            }
            var cities = self.cities;
            if (cities.indexOf(",") != -1) {
                cities = cities.split(",");
            } else {
                cities = [cities];
            }
            var _orderType;
            if (!self.searchVal) {
                _orderType = 1;
            }
            var data = {
                "gmtCreateStart": gmt,
                "orderType": _orderType,
                "gmtCreateEnd": gmt,
                "operator": $.cookie('_uk'),
                "sellerListStatus": self.status == 7 ? 3 : self.status,
                "pageSize": self.pageSize,
                "pageNum": self.pageNum,
                "shopIdList": self.shopId, //[3573, 4587, 4682]
                "cityCodeList": cities
            };
            if (self.status == 3 || self.status == 7) {
                $.extend(data, {
                    "logisticsStatus": self.logisticStatus,
                    "sendTimeRange": self.sendTimeRange
                });
            }
            //显示加载图标
            $('#order').html('<div class="text-center"><i class="fa fa-spinner fa-spin fa-3x fa-fw loading"></i></div>');
            CRM.request({
                "type": 'POST',
                "url": CRM.API.queryOrderList,
                "dataType": "json",
                "data": JSON.stringify(data),
                "success": function(req) {
                    var entry = req.entry;
                    if (req.status) {
                        CRM.getServerTime(function(serverTime) {
                            if (entry.length > 0) {
                                $.each(entry, function(index, item) {
                                    if (item.payType == 2 && item.payStatus == 2) {
                                        item.time = (serverTime - item.buyer2uspayTime) / 60 / 1000
                                    } else {
                                        item.time = (serverTime - item.gmtCreate) / 60 / 1000
                                    }
                                });
                            }
                            if (self.status == 3 || self.status == 7)
                                self.cacheEntries[self.status][self.sendTimeRange][self.pageNum] = entry;
                            else
                                self.cacheEntries[self.status][self.pageNum] = entry;
                            $('#order').html(listTpl({
                                data: entry
                            }));
                            self.enabledTabFn();
                        })
                    } else {
                        CRM.showDialog(req.message);
                        self.enabledTabFn();
                    }
                }
            });
        },

        /**
         * 获取不同配送时长下得订单数量
         */
        queryOrderListCount: function() {
            var self = this,
                gmt = self.gmt;
            if (!$.isArray(this.shopId)) {
                if (this.shopId) {
                    this.shopId = [this.shopId];
                } else {
                    this.shopId = [];
                }
            }
            var cities = self.cities;
            if (cities.indexOf(",") != -1) {
                cities = cities.split(",");
            } else {
                cities = [cities];
            }
            var _orderType;
            if (!self.searchVal) {
                _orderType = 1;
            }
            var data = {
                "gmtCreateStart": gmt,
                "orderType": _orderType,
                "gmtCreateEnd": gmt,
                "operator": $.cookie('_uk'),
                "sellerListStatus": 3,
                "shopIdList": self.shopId, //[3573, 4587, 4682]
                "cityCodeList": cities,
                "sendTimeRange": self.sendTimeRange
            };
            CRM.request({
                "type": 'POST',
                "url": CRM.API.queryOrderListCount,
                "dataType": "json",
                "data": JSON.stringify($.extend({},data,{"logisticsStatus": 2})),
                "success": function(req) {
                    var entry = req.entry;
                    if (req.status) {
                        var node = $('.nav-tabs li:eq(2) a[data-status]');
                        node.html(node.html().replace(/\(.*\)/, '(' + entry + ')'));
                        node.attr('data-total', entry);
                        self.cacheEntries[self.sendTimeRange][2]=entry;
                        if($('.nav-tabs li.active a').attr('data-logistic-status')=='2'){
                            self.total = $('.nav-tabs li.active a').attr('data-total');
                            self.initPagination();
                        }
                    }
                }
            });
            CRM.request({
                "type": 'POST',
                "url": CRM.API.queryOrderListCount,
                "dataType": "json",
                "data": JSON.stringify($.extend({},data,{"logisticsStatus": 3})),
                "success": function(req) {
                    var entry = req.entry;
                    if (req.status) {
                        var node = $('.nav-tabs li:eq(3) a[data-status]');
                        node.html(node.html().replace(/\(.*\)/, '(' + entry + ')'));
                        node.attr('data-total', entry);
                        self.cacheEntries[self.sendTimeRange][3]=entry;
                        if($('.nav-tabs li.active a').attr('data-logistic-status')=='3'){
                            self.total = $('.nav-tabs li.active a').attr('data-total');
                            self.initPagination();
                        }
                    }
                }
            });
        },

        /**
         * 查询结果缓存初始化
         */
        initCacheEntries: function() {
            this.cacheEntries = {
                //所有订单信息缓存
                '1': {},
                '2': {},
                '3': {
                    '': {},
                    '0-40': {},
                    '40-60': {},
                    '60-120': {},
                    '120-180': {},
                    '180': {}
                },
                '6': {},
                '7': {
                    '': {},
                    '0-40': {},
                    '40-60': {},
                    '60-120': {},
                    '120-180': {},
                    '180': {}
                },
                //配送时长筛选后总数缓存
                '': {},
                '0-40': {},
                '40-60': {},
                '60-120': {},
                '120-180': {},
                '180': {}
            };
        },

        /**
         * bootstrap时间控件初始化
         */
        initDatetimePicker: function() {
            $('.form_date').datetimepicker({
                language: 'zh-CN',
                weekStart: 1,
                todayBtn: 1,
                autoclose: 1,
                todayHighlight: 1,
                startView: 2,
                minView: 2,
                forceParse: 0
            });
        },

        /**
         * bootstrap分页控件初始化
         * @param total 总数量
         */
        initPagination: function() {
            var self = this,
                _total = (self.total == 0) ? 1 : self.total;
            //reset
            $('.pagination').html('<div id="pagination"></div>');
            //init
            $('#pagination').twbsPagination({
                totalPages: Math.ceil(_total / this.pageSize),
                visiblePages: 10,
                onPageClick: function(event, page) {
                    self.disabledTabFn();
                    self.pageNum = page;
                    if (self.status == 3 || self.status == 7) {
                        if ($.isEmptyObject(self.cacheEntries[self.status][self.sendTimeRange][self.pageNum]) && self.total != 0)
                            self.queryOrderList();
                        else {
                            $('#order').html(listTpl({
                                data: self.cacheEntries[self.status][self.sendTimeRange][self.pageNum]
                            }));
                            self.enabledTabFn();
                        }
                    } else {
                        if ($.isEmptyObject(self.cacheEntries[self.status][self.pageNum]) && self.total != 0)
                            self.queryOrderList();
                        else {
                            $('#order').html(listTpl({
                                data: self.cacheEntries[self.status][self.pageNum]
                            }));
                            self.enabledTabFn();
                        }
                    }
                }
            });
        },

        disabledTabFn: function() {
            this.disabledTab = true;
            var target = $('.nav-tabs li:not(.active)').find('a');
            target.addClass('disabled');
            target.focus(function(event) {
                this.blur();
            });
        },
        enabledTabFn: function() {
            this.disabledTab = false;
            var target = $('.nav-tabs li:not(.active)').find('a').removeClass('disabled');
            target.removeClass('disabled');
        },

        bindEvent: function() {
            var self = this;

            $(document).on('click', '#J_SearchBtn', function() {
                $('#dist_time_group').hide();
                self.searchVal = $('#search-input').val();
                self.status = 1;
                self.queryShopId(function() {
                    $('#dist_time').val('');
                    self.sendTimeRange = '';
                    $('#dist_time').removeClass('filter');
                    self.renderTab();
                });
            });

            $(document).on('click', '.order-item', function() {
                orderDetail.init($(this).attr('data-id'));
            });

            $(document).on('change', '#page_size', function() {
                self.pageSize = this.value;
                self.pageNum = 1;
                self.initCacheEntries();
                self.initPagination();
            });

            $(document).on('change', '#dist_time', function() {
                self.sendTimeRange = this.value;
                self.pageNum = 1;
                if($.isEmptyObject(self.cacheEntries[this.value]))
                    self.queryOrderListCount();
                else{
                    //如果订单数量有缓存，则从缓存中取数据
                    var node2 = $('.nav-tabs li:eq(2) a[data-status]');
                    var node3 = $('.nav-tabs li:eq(3) a[data-status]');
                    node2.html(node2.html().replace(/\(.*\)/, '(' + self.cacheEntries[this.value][2] + ')'));
                    node3.html(node3.html().replace(/\(.*\)/, '(' + self.cacheEntries[this.value][3] + ')'));
                    node2.attr('data-total', self.cacheEntries[this.value][2]);
                    node3.attr('data-total', self.cacheEntries[this.value][3]);
                    self.total = $('.nav-tabs li.active a').attr('data-total');
                    self.initPagination();
                }
                if (this.value != '')
                    $(this).addClass('filter');
                else
                    $(this).removeClass('filter');
            });


        }
    };



    return List;
});